package com.ceicei.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zhz.project.common.util.date.DateUtils;

public class GetWebContent {
    private static Log logger = LogFactory.getLog(GetWebContent.class);

    public static String getCustomedBinaryContent(String strUrl, String name) {
        return getCustomedContent(strUrl, true, name);
    }

    private static String getCustomedContent(String strUrl, boolean binary, String name) {
        FileOutputStream os = null;
        try {
            HttpClient client = new HttpClient();
            HttpMethod method = new GetMethod(strUrl);
            method.setRequestHeader("Connection", "close");
            List<Header> headers = new ArrayList<Header>();

            client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);

            client.executeMethod(method);

            if (!binary) {
                return method.getResponseBodyAsString();
            } else {
                byte[] b = method.getResponseBody();
                String fileName = DateUtils.dtLongMillFormat(new Date());
                os = new FileOutputStream(CeiceiConstants.FILE_ROOT + "/" + name + "_" + fileName
                                          + ".png");
                os.write(b);

                os.flush();
                return CeiceiConstants.FILE_ROOT + "/" + name + "_" + fileName + ".png";
            }
        } catch (Exception e) {
            logger.error("异常", e);
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                logger.error("异常", e);
            }

        }
        return null;
    }
}
